import { urlUtil } from '@mtjs/utils';

/**
 * 末尾添加'/'
 * @param  path 路径
 */
export function trailingSlash(path) {
  return path.endsWith('/') ? path : path + '/';
}

/**
 * 绝对URL跳转
 * @param {string} url 目标URL
 * @param {boolean} replace 是否使用replace方式跳转
 */
export function absoluteGo(url, replace = false) {
  try {
    window.location[replace ? 'replace' : 'assign'](url);
  } catch (e) {
    window.location.href = url;
  }
}

// 判断是否是绝对路径
export function isAbsoluteUrl(url) {
  return /^(https?:\/\/|\/\/)[\w.]+\/?/gi.test(url);
}

export const isOnline = () => {
  return window.location.hostname.endsWith('.com');
};

export function getMTLocationOrigin() {
  return isOnline() ? `https://www.mytijian.com` : 'http://m-test.mytijian.cn';
}

/**
 * 获取OSS路径
 * @param {string} path 路径
 * @returns 返回拼装后的完整路径
 */
export function getOSSBaseUrl(path = '') {
  if (path.startsWith('http')) return path;
  const onlineOssUrl = 'https://mytijian-img.oss-cn-hangzhou.aliyuncs.com/';
  const testOssUrl = 'https://test-i.oss-cn-shanghai.aliyuncs.com/';

  return (isOnline() ? onlineOssUrl : testOssUrl) + path;
}

/**
 * 生成完整的跳转路径
 */
export function buildFullUrl(url, params) {
  const origin = window.location.origin;
  return urlUtil.buildUrl(origin + url, params);
}

/**
 * callback 链接增加参数或修改参数
 * @param callback
 * @param key
 * @param val2
 * @returns {*}
 */
export function parseCallbackUrl(callback, key, val2) {
  if (!callback) {
    return '';
  }
  callback = callback.replace(/#$/, '');
  if (callback.indexOf('?') === -1) {
    callback = callback + '?' + key + '=' + val2;
  } else if (callback.indexOf('&' + key + '=') === -1 && callback.indexOf('?' + key + '=') === -1) {
    callback = callback + '&' + key + '=' + val2;
  } else {
    const regExp = new RegExp('([&?]' + key + '=)[^&]*', '');
    callback = callback.replace(regExp, '$1' + val2);
  }
  return callback;
}
export function safeJSONParse(str) {
  let res = '';
  try {
    res = JSON.parse(str);
  } catch (error) {
    res = '';
  }
  return res;
}
